import sys
import os
import time
#sys.path.append('..'+os.sep+'trunk')
sys.path.append('../../../')
from spade import *
class Example(Agent.Agent):
    def _setup(self):
        entry = "Starting Organization Behaviour"
        self.info=[{"Recurso":"Museo","Nombre":"Museo","Tipo":"Arte Moderno","Calle":"lacalle2","Horario":"8h-19h"}]




    def _process(self):
     pass
class MyOrganization(Bureaucracy.Bureaucracy):
    def _process(self):
        time.sleep(2000)

class MyUnit(Unit.Hierarchy):
    def onStart(self):
        time.sleep(10)
        template = Behaviour.ACLTemplate()
        template.setProperty("from",self.name)
        template.setPerformative("inform")
        template.setOntology("spade:x:unit")
        t = Behaviour.MessageTemplate(template)
        self.gotoBehaviour=self.GotoBehaviour(self)
        self.myAgent.addBehaviour(self.gotoBehaviour, t)

    class GotoBehaviour(Behaviour.Behaviour):
        def __init__(self,unit):
            self.unit=unit
            Behaviour.Behaviour.__init__(self)

        def _process(self):
            m= self._receive(True)
            if m and m.getProperty("from")==self.unit.name:
                print "Dentro de la unidad:"+self.unit.name
                unitName=m.getContent().split(":")[1]
                u=MyUnit(self.myAgent, nick=self.unit.nick, password="pass", name=unitName)
                print "Tratando de entrar en "+unitName
                d=[{"name":"rol","value":"fuentes de informacion"}]
                entry=self.unit.requestEntryUnit(unitName,d)
                self.unit.joinUnit(u)
                self.myAgent.removeBehaviour(self)

    def _process(self):
            print "Dentro de la unidad:"+self.name
            mens=self.receiveMessage()
            while not mens and self.state!="unavailable":
              mens=self.receiveMessage()
            content=[]
            if mens:
                print mens
                for i in self.myAgent.info:
                    recurso=mens.getContent().split(":")[0]
                    tipo=mens.getContent().split(":")[1]
                    if i["Tipo"]==tipo and recurso==i["Recurso"]:
                        content.append(i)
                if content!=[]:
                    ans=ACLMessage.ACLMessage()
                    ans.setPerformative("inform")
                    ans.setSender(self.myAgent.getAID())
                    ans.addReceiver(mens.getSender())
                    ans.setContent(str(content))
                    self.sendPrivateMessage(ans,mens.getSender().getName())



if __name__ == "__main__":
    agent = "siteb@apolo.dsic.upv.es"
    b = Example(agent,"pasword")
    b.nick="eeooe"
    b.start()
    time.sleep(5)
    lista= b.getOrganizationList()
    for i in lista:
        info=b.getOrganizationInfo(i)
        goal=info["goal"]
        g=eval(goal)
        if g.has_key("necesita") and g["necesita"]=="fuentes de informacion turistica":
            o=MyOrganization(b,nick="fuenteB", name=i)
            b.joinOrganization(o)
            l=o.getUnitList()
            for u in l:
                info=o.getUnitInfo(u)
                if info["type"]=="Hierarchy" and eval(info["goal"])["necesita"]=="fuentes de informacion":
                    unit=MyUnit(b, nick="fuenteB", password="pass", name=u)
                    try:
                        o.joinUnit(unit)
                    except Unit.MembersOnly:
                                    print "Excepcion:MembersOnly"
                                    d=[{"name":"rol","value":"fuentes de informacion"}]
                                    entry=o.requestEntryUnit(u,d)
                                    if entry:
                                            m=MyUnit(b, nick="fuenteB", password=entry,name=u)
                                            o.joinUnit(m)




